//
//  CZEmotionCollectionViewCell.swift
//  weibo
//
//  Created by Apple on 16/3/20.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit

//  每页表情视图的cell
class CZEmotionCollectionViewCell: UICollectionViewCell {
    //  图片按钮
    private lazy var emoticonsButton: [CZEmoticonButton] = [CZEmoticonButton]()
    //  设置数据
    var emoticons: [CZEmoticon]? {
        didSet {
            guard let emts = emoticons else {
                return
            }
            
            //  cell复用解决方案，，先让全部按钮隐藏，设置一张图片，显示出来一张
            
            for button in emoticonsButton {
                button.hidden = true
            }
            
            for (i,value) in emts.enumerate() {
                print(value)
                let button = emoticonsButton[i]
                button.hidden = false
                button.emoticon = value
                
                //if value.type == "0" {
                    
//                    let bundlePath = NSBundle.mainBundle().pathForResource("Emoticons", ofType: "bundle")!
//                    let emoticoneBundle = NSBundle(path: bundlePath)
//                    
//                    let path = (emoticoneBundle!.pathForResource("default", ofType: nil)! as NSString).stringByAppendingPathComponent(value.png!)
//                    
//                    button.setImage(UIImage(named: path), forState: .Normal)
               // }
                
            }
            
            
        }
    }
    var indexPath: NSIndexPath? {
        didSet{
//            messageLabel.text = "第\(indexPath?.section ?? 0)组,第\(indexPath?.item ?? 0)行"
            // 判断如果是第一组显示label，否则隐藏
            recentMessageLabel.hidden = indexPath?.section != 0
            
        }
    }
    
    //  添加一个label用于显示
    private lazy var messageLabel: UILabel = {
        let label = UILabel()

        label.textAlignment = .Center
        return label
    }()
    //  删除按钮
    private lazy var deleteButton: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: "deleteButtonClick", forControlEvents: .TouchUpInside)
        button.setImage(UIImage(named: "compose_emotion_delete"), forState: .Normal)
        button.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: .Highlighted)
        return button
    }()
    //  消息文本
    private lazy var recentMessageLabel: UILabel = {
        let label = UILabel(textColor: UIColor.grayColor(), fontSize: 12)
        label.text = "最近使用表情"
        return label
    }()
    
    //  懒加载popview
    private lazy var popView: CZEmoticonPopView =  CZEmoticonPopView.emoticonPopView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        addEmoticonButton()
        contentView.addSubview(deleteButton)
        contentView.addSubview(recentMessageLabel)
//        contentView.addSubview(messageLabel)
//
//        messageLabel.snp_makeConstraints { (make) -> Void in
//            make.center.equalTo(contentView)
//        }
        
        recentMessageLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.bottom.equalTo(self).offset(-10)
        }
        
        //  添加长按手势
        let longGest = UILongPressGestureRecognizer(target: self, action: "longGestAction:")
        contentView.addGestureRecognizer(longGest)
        
    }
    //  添加图片按钮
    private func addEmoticonButton() {
        for _ in 0..<EmoticonNumOfPage {
            let button = CZEmoticonButton()
            button.addTarget(self, action: "emoticonClick:", forControlEvents: .TouchUpInside)
            //  设置按钮字体大小
            button.titleLabel?.font = UIFont.systemFontOfSize(34)
            button.backgroundColor = RandomColor()
            contentView.addSubview(button)
            emoticonsButton.append(button)
        }
    }
    
    // MARK:    表情按钮点击事件
    
    @objc private func deleteButtonClick() {
        NSNotificationCenter.defaultCenter().postNotificationName(CZDeleteEmoticonNotification, object: nil)
    }
    
    @objc private func longGestAction(gesture: UILongPressGestureRecognizer) {
        //  获取长按的点
        let location = gesture.locationInView(contentView)
        print(location)
        
        func emoticonbuttonWithPoint(point: CGPoint) -> CZEmoticonButton?{
            //  对比按钮的rect是否包含这个点，如果包含弹出popview,设置数据显示
            var targetButton: CZEmoticonButton?
            for button in emoticonsButton {
                if CGRectContainsPoint(button.frame, location) {
                    
                    targetButton = button
                    
                    break
                }
            }
            return targetButton
        }
       
        //  查找按钮只在开始或者移动的时候操作
        switch gesture.state {
        case .Began, .Changed:
            //  获取找到的button
            if let targetButton = emoticonbuttonWithPoint(location) {
                //  显示popview，在button的位置
                targetButton.showPopView(popView)
            }
        case .Ended:
            if let targetButton = emoticonbuttonWithPoint(location) {
                //  手势结束后设置文本框内容
                emoticonClick(targetButton)
            }
            //  隐藏popView
            popView.hidden = true
        default:
            //  未知状态隐藏掉popView
            popView.hidden = true
        }
        
    }
    
    @objc private func emoticonClick(button: CZEmoticonButton) {
        
        //  获取表情按钮对应的数据
        let emoticon = button.emoticon
        print(emoticon?.chs)
        
        //  层级太深，使用通知告诉composeviewcontroller
        NSNotificationCenter.defaultCenter().postNotificationName(CZEmoticonNotification, object: emoticon)
        
        let popView = CZEmoticonPopView.emoticonPopView()
        button.showPopView(popView)
//        //  添加到window上
//        let window = UIApplication.sharedApplication().windows.last!
//        //  popView的坐标,需要让点击的button进行坐标转换，让其两个在同一个坐标系中
//        let rect = button.convertRect(button.bounds, toView: window)
//        //  中心点x等于转换户按钮的中心点x
//        popView.center.x = CGRectGetMidX(rect)
//        //  y轴等于button的底部-一个popview的高度，相当于和按钮底部对齐
//        popView.y = CGRectGetMaxY(rect) - popView.height
//        //  设置显示数据
//        popView.emoticonButton.emoticon = button.emoticon
//        window.addSubview(popView)
        
        
        //  移除popview
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.1 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            popView.removeFromSuperview()
        }
        
    }
    
    //  子按钮的frame改变在layoutsubview中实现
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let leftMargin: CGFloat = 5
        let buttomMargin: CGFloat = 25
        
        //  图片按钮的宽度
        let itemW = (contentView.width - leftMargin * 2) / CGFloat(EmoticonColOfPage)
        //  图片按钮的高度
        let itemH = (contentView.height - buttomMargin) / CGFloat(EmoticonRowOfPage)
        
        for (i, value) in emoticonsButton.enumerate() {
            //  设置大小
            value.size = CGSize(width: itemW, height: itemH)
            //  计算列和行的索引
            let col = i % EmoticonColOfPage
            let row = i / EmoticonColOfPage
            //  按钮的坐标
            value.x = CGFloat(col) * itemW + leftMargin
            value.y = CGFloat(row) * itemH
            
        }
        deleteButton.size =  CGSize(width: itemW, height: itemH)
        deleteButton.x = contentView.width - itemW - leftMargin
        deleteButton.y = contentView.height - itemH - buttomMargin
    }
    
}
